export const QuadNode = function (val, isLeaf, topLeft, topRight, bottomLeft, bottomRight) {
  this.val = val ?? null
  this.isLeaf = isLeaf ?? null
  this.topLeft = topLeft || null
  this.topRight = topRight || null
  this.bottomLeft = bottomLeft || null
  this.bottomRight = bottomRight || null
}

export const createTreeByArray = function (arr) {
  if (arr.length === 0) return null
  const [isLeaf, val] = arr[0]
  console.log('isLeaf', isLeaf, 'val', val)
  const root = new QuadNode(val, !!isLeaf)
  const queue = [root]
  let i = 0
  const nodePos = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']
  while (queue.length > 0 && i < arr.length) {
    const node = queue.shift()
    if (!node) continue
    // let tempIsLeaf = true
    // let sumVal = 0
    for (const pos of nodePos) {
      i++
      if (i >= arr.length) break
      if (!arr[i]) continue
      // console.log(arr)
      const [isLeaf, val] = arr[i]
      node[pos] = new QuadNode(val, !!isLeaf)
      queue.push(node[pos])
      // tempIsLeaf = tempIsLeaf && isLeaf
      // sumVal += val
    }
  }
  console.log(root)
  return root
}

export const treeToArray = function (node) {
  if (!node) return []
  const queue = [node]
  const res = []
  while (queue.length > 0) {
    const sz = queue.length
    for (let i = 0; i < sz; i++) {
      const node = queue.shift()
      if (!node) continue
      res.push([node.isLeaf ? 1 : 0, node.val])
      for (const pos of ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']) {
        queue.push(node[pos])
      }
    }
  }
  return res
}
